/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import sun.misc.BASE64Encoder;

/**
 *
 * @author Ahmed
 */
@Named(value = "controller")
@SessionScoped
public class UserController implements Serializable {

    /**
     * Creates a new instance of UserController
     */
    public UserController() {
    }

    public void logout(ActionEvent event) {

        System.out.println("loging out");
       
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
         HttpSession session=(HttpSession) ec.getSession(true);
         
        /* Enumeration<String> e=session.getAttributeNames();
         
         while(e.hasMoreElements()){
             String s=e.nextElement();
             System.out.println("name="+s);
         }*/
        session.invalidate();
         try {
         ec.redirect(((HttpServletRequest) ec.getRequest()).getRequestURI());
         } catch (IOException ex) {
         Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
         }
         
    }

    public synchronized String encrypt(String plaintext) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-256"); //step 2
        } catch (NoSuchAlgorithmException e) {

        }
        try {
            md.update(plaintext.getBytes("UTF-8")); //step 3
        } catch (UnsupportedEncodingException e) {

        }

        byte raw[] = md.digest(); //step 4
        String hash = (new BASE64Encoder()).encode(raw); //step 5
        return hash; //step 6
    }
}
